import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { fetchAddStoryBuySlice, fetchGetStoryBuySlice, fetchDeleteStoryBuySlice } from './buyStory.action';


export interface IResponse {
	balls: IOneBall[], 
	user: {
		email: string,
		fullName: string,
		id: number
		}
	id: number,
	totalSumm: number
	}

export interface IOneBall {
		id: number;
		name: string;
		image: string;
		price: number;
		count: number;
		title: string;
		description: string;
		favorite?: boolean;
	}

export interface IGetResBalls {
	storyBuy: IResponse[],
	loading: boolean,
	errors: null,
	success: boolean
}

const initialState: IGetResBalls = {
	storyBuy: [],
	loading: false,
	errors: null,
	success: false
};

export const buyStorySlice = createSlice({
	name: 'buyStory',
	initialState,
	reducers: {
	},
	extraReducers: (builder) => {
		builder.addCase(fetchAddStoryBuySlice.pending, (state) => {
			state.loading = true;
			state.errors = null;
		});
		builder.addCase(
			fetchAddStoryBuySlice.fulfilled,
			(state) => {
				state.loading = false;
			}
		);
		builder.addCase(fetchAddStoryBuySlice.rejected, (state, action) => {
			// state.loading = true;
			state.errors = action.error.message;
		}),
		builder.addCase(fetchGetStoryBuySlice.pending, (state) => {
			state.loading = true;
			state.errors = null;
		});
		builder.addCase(
			fetchGetStoryBuySlice.fulfilled,
			(state, action: PayloadAction<IResponse[]>) => {
				console.log('мячики из истории покупок', action.payload);
				state.storyBuy = action.payload;
				state.loading = false;
			}
		);
		builder.addCase(fetchGetStoryBuySlice.rejected, (state, action) => {
			// state.loading = true;
			state.errors = action.error.message;
		}),
		builder.addCase(fetchDeleteStoryBuySlice.pending, (state) => {
			state.success = false;
			state.loading = true;
			state.errors = null;
		});
		builder.addCase(
			fetchDeleteStoryBuySlice.fulfilled,
			(state, action) => {
				console.log('мячики из истории после удаления', action.payload);
				// state.storyBuy = action.payload;
				state.loading = false;
				state.success = true;
			}
		);
		builder.addCase(fetchDeleteStoryBuySlice.rejected, (state, action) => {
			// state.loading = true;
			state.errors = action.error.message;
		});
	}
});

export default buyStorySlice.reducer;

